package thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class DiedReentrantLockTryLock extends Thread {
    static ReentrantLock reentrantLock1 = new ReentrantLock(true);

    static ReentrantLock reentrantLock2 = new ReentrantLock(true);

    int i = 1;

    public static void main(String[] args) {
        DiedReentrantLockTryLock zhangsan = new DiedReentrantLockTryLock(1, "zhangsan");
        DiedReentrantLockTryLock lisi = new DiedReentrantLockTryLock(2, "lisi");
        zhangsan.start();
        lisi.start();

    }

    public DiedReentrantLockTryLock(int i, String name) {
        super(name);
        this.i = i;
    }

    @Override
    public void run() {
        if (i==1){
            try {
                reentrantLock1.tryLock(20,TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                reentrantLock2.tryLock(20,TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }else if (i==2){
            try {
                reentrantLock2.tryLock(20,TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                reentrantLock1.tryLock(20,TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if (reentrantLock1.isHeldByCurrentThread()){
            reentrantLock1.unlock();
        }
        if (reentrantLock2.isHeldByCurrentThread()){
            reentrantLock2.unlock();
        }
    }
}
